package com.huike.game.Activity;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.huike.game.R;
import com.huike.game.api.Api;
import com.huike.game.base.Game15;
import com.huike.game.dao.AccountDao;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class GameActivity15 extends AppCompatActivity {


    private ListView lv_game15;
    private List<Game15.DataBean> list;
    private  RequestQueue queue;
    private ViewsAdapter adapter;
    private ProgressDialog show;
    private AccountDao dao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game15);
        initView();


        try {
            dao  = new AccountDao(GameActivity15.this);
            List<Game15.DataBean> list = dao.queryAll();
            Log.e("---",list.toString() + "mmmmm");
            Log.e("---", "cccccc");

        } catch (SQLException e) {
            e.printStackTrace();
        }

        list = new ArrayList<>();

        initDate();
    }

    private void setProgressDialog(String title,String msg){
        if(show == null ){
            show = ProgressDialog.show(this, title, msg);
            show.show();
        }
    }
    private void  hideProgressDialog(){

        if(show.isShowing() && show != null){
            show.dismiss();
        }

    }

    private void initDate() {

        setProgressDialog("提示","加载中...");

        queue = Volley.newRequestQueue(this);

        JsonObjectRequest request = new JsonObjectRequest(1, Api.api + "accountList", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
//                Log.e("-----",jsonObject.toString());
                Game15.DataBean bean;
                try {
                    JSONObject object = new JSONObject(jsonObject.toString());
                    JSONArray data = object.getJSONArray("data");
                    for(int i= 0;i<data.length();i++){
                       bean =  new Game15.DataBean();
                        JSONObject object1 = data.getJSONObject(i);
                        String id = object1.getString("id");
                        String image = object1.getString("image");
                        String carNumber = object1.getString("carNumber");
                        String carName = object1.getString("carName");
                        String balance = object1.getString("balance");
                        bean.setId(id);
                        bean.setImage(image);
                        bean.setCarNumber(carNumber);
                        bean.setCarName(carName);
                        bean.setBalance(balance);
                        list.add(bean);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                adapter = new ViewsAdapter();
                lv_game15.setAdapter(adapter);

                hideProgressDialog();

            }
        },null);

        queue.add(request);


    }

    private void initView() {
        lv_game15 = (ListView) findViewById(R.id.lv_game15);
    }

    class ViewsAdapter extends BaseAdapter {


        @Override
        public int getCount() {

            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {

            ViewHolder holder = null;

            if (view == null) {
                view = View.inflate(GameActivity15.this, R.layout.lv_game15, null);
                holder = new ViewHolder(view);

                holder.tv_game15_carNumber.setText(list.get(i).getCarNumber());
                holder.cb_game15.setChecked(list.get(i).getCheck());
                holder.tv_game15_balance.setText(list.get(i).getBalance());
                holder.tv_game15_carName.setText(list.get(i).getCarName());
                holder.tv_game15_id.setText(list.get(i).getId());

                final ViewHolder finalHolder = holder;
                ImageRequest request = new ImageRequest(list.get(i).getImage(), new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                        finalHolder.iv_game15_image.setImageBitmap(bitmap);
                    }
                }, 0, 0, ImageView.ScaleType.CENTER, Bitmap.Config.ARGB_8888, null);

                queue.add(request);

                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            final ViewHolder finalHolder1 = holder;
            holder.cb_game15.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(finalHolder1.cb_game15.isChecked()){
                        list.get(i).setCheck(true);
                        adapter.notifyDataSetChanged();
                    }else{
                        list.get(i).setCheck(false);
                        adapter.notifyDataSetChanged();
                    }
                }
            });


            holder.btn_game15.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    final StringBuffer buffer = new StringBuffer();
                    for (int i = 0; i< list.size();i ++){
                        if(list.get(i).getCheck()){
                            buffer.append(list.get(i).getCarNumber()).append(" ");
                        }
                    }
                     final AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity15.this);
                     final AlertDialog dialog = builder.create();
                    final View inflate = View.inflate(GameActivity15.this, R.layout.recharge_game15, null);
                    TextView tv =   inflate.findViewById(R.id.tv_game15_carNumber_alert);
                    tv.setText(buffer.length() <=  0  ? list.get(i).getCarNumber() : buffer);
                    Button  confirm =   inflate.findViewById(R.id.btn_game15_confirm);
                    Button cancle =   inflate.findViewById(R.id.but_game15_cancel);
                    dialog.setView(inflate);
                    dialog.show();


                    confirm.setOnClickListener(new View.OnClickListener() {
                        String[] split;
                        @Override
                        public void onClick(View view) {

                            EditText et =   inflate.findViewById(R.id.et_game15_price_alert);
                            final String value_input  = et.getText().toString();

                            if( value_input.length() == 0 || "".equals(value_input)){
                                Toast.makeText(GameActivity15.this, "只能是1-999之间", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            if(Integer.parseInt(value_input) > 999 || Integer.parseInt(value_input)  <= 0){
                                Toast.makeText(GameActivity15.this, "只能是1-999之间", Toast.LENGTH_SHORT).show();
                                return;
                            }


                            JSONObject object = new JSONObject();
                            try {
                                object.put("price","1");
                                if(buffer.length() == 0){
                                    String number = list.get(i).getCarNumber();
//                                    Log.e("---",number +"----");
                                    if(number.equals("辽A10001")){
                                        object.put("price1",value_input);
                                    }else if(number.equals("辽A10002")){

                                        object.put("price2",value_input);
                                    }else if(number.equals( "辽A10003")){

                                        object.put("price3",value_input);
                                    }else  if(number.equals("辽A10004") ){
                                        object.put("price4",value_input);
                                    }
                                }else{

                                    Log.e("---",buffer.toString());
                                   split  = buffer.toString().split(" ");
                                    for(int i=0; i<split.length;i++){
                                        if(split[i].equals("辽A10001")){
                                            object.put("price1",value_input);
                                        }else if(split[i].equals("辽A10002")){
                                            object.put("price2",value_input);
                                        }else if(split[i].equals("辽A10003")){
                                            object.put("price3",value_input);
                                        }else if(split[i].equals("辽A10004")){
                                            object.put("price4",value_input);
                                        }
                                    }

                                }
                                Log.e("----",object.toString());

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            list.clear();

                            setProgressDialog("提示","加载中...");

                            JsonObjectRequest request = new JsonObjectRequest(1, Api.api + "accountList", object.toString(), new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject jsonObject) {

                                    try {
                                        JSONObject rel = new JSONObject(jsonObject.toString());
                                        JSONArray data = rel.getJSONArray("data");
                                        Game15.DataBean bean;
                                        for (int i = 0; i < data.length(); i++) {
                                            JSONObject dataJSONObject = data.getJSONObject(i);
                                            bean = new Game15.DataBean();
                                            String id = dataJSONObject.getString("id");
                                            String image = dataJSONObject.getString("image");
                                            String carNumber = dataJSONObject.getString("carNumber");
                                            String carName = dataJSONObject.getString("carName");
                                            String balance = dataJSONObject.getString("balance");
                                            bean.setId(id);
                                            bean.setImage(image);
                                            bean.setCarNumber(carNumber);
                                            bean.setCarName(carName);
                                            bean.setBalance(balance);
                                            list.add(bean);
                                        }

                                        lv_game15.setAdapter(adapter);
//                                        adapter.notifyDataSetChanged();
                                        hideProgressDialog();
                                        dialog.dismiss();


                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

//                                    保存数据库
                                        if(buffer.toString().length() == 0 || "".equals(buffer.toString())){
                                            Game15.DataBean bean = new Game15.DataBean(list.get(i).getCarNumber(),list.get(i).getCarName(),new Date().getTime(),value_input,list.get(i).getBalance());
                                            dao.save(bean);
                                        }else{
                                            for(int i =0; i <split.length; i++ ){
                                                Game15.DataBean bean = new Game15.DataBean(split[i],list.get(i).getCarName(),new Date().getTime(),value_input,list.get(i).getBalance());//这里有一个BUG i 是for得下标  不是选中得
                                                dao.save(bean);
                                            }
                                        }

                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("-----",volleyError.getMessage());
                                }
                            });

                            queue.add(request);

                        }
                    });


                    cancle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    });


                }
            });

            return view;
        }


        class ViewHolder {
            public View rootView;
            public TextView tv_game15_id;
            public TextView tv_game15_carNumber;
            public TextView tv_game15_carName;
            public TextView tv_game15_balance;
            public Button btn_game15;
            public CheckBox cb_game15;
            public ImageView iv_game15_image;

            public ViewHolder(View rootView) {
                this.rootView = rootView;
                this.tv_game15_id = (TextView) rootView.findViewById(R.id.tv_game15_id);
                this.tv_game15_carNumber = (TextView) rootView.findViewById(R.id.tv_game15_carNumber);
                this.tv_game15_carName = (TextView) rootView.findViewById(R.id.tv_game15_carName);
                this.tv_game15_balance = (TextView) rootView.findViewById(R.id.tv_game15_balance);
                this.btn_game15 = (Button) rootView.findViewById(R.id.btn_game15);
                this.cb_game15 = rootView.findViewById(R.id.cb_game15);
                this.iv_game15_image = rootView.findViewById(R.id.iv_game15_image);
            }

        }
    }
}
